<template>
  <a-descriptions :data="basicInfo" :column="2" :label-style="{ textAlign: 'right' }" bordered>
    <template #label="{ label, data }">
      <div :class="[data.required ? 'required' : '']" :style="{ color: label == '合计服务费' ? 'red' : 'block' }">{{ label }}：</div>
    </template>
    <template #value="{ value, data }">
      <div v-if="data.label == '任务创建人'">{{ userInfo.userName }}</div>
      <div v-if="data.label == '任务雇主'" style="width: 600px">
        <a-space>
          <a-select @change="changeUser" v-model="form.employer.id" allow-search :style="{ width: '200px' }">
            <a-option v-for="item of userList" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
          <div class="common-text">任务雇主才是任务的真实所属任务，默认是SKU的销售员</div>
        </a-space>
      </div>
      <div v-if="data.label == '任务验收人'" style="width: 200px">
        <div>
          <span>{{ form.verifyerList.map((e: any) => e.name).join(',') }}</span>
          <!-- <span v-if="form.userName != userInfo.userName && form.userName">,{{ form.userName }}</span> -->
        </div>
        <div class="common-text">多个验收人只需其中1人验收通过即可</div>
      </div>
      <div v-if="data.label == '接单组织'">
        <a-button type="primary" @save="comSave" @click="showTakeOrder = true">请选择</a-button>
        <div class="common-text" style="margin-top: 5px" v-if="form.takeCompany.companyShortName">
          <span>{{ form.takeCompany.companyShortName }}</span>
          <span @click="delCom" class="cursor" style="margin-left: 5px"><icon-close /></span>
        </div>
      </div>

      <div v-if="data.label == '期望交付日期'">
        <a-date-picker style="width: 200px" :disabledDate="disableDate" v-model="form.gmtExpectDelivery" value-format="timestamp" placeholder="请选择" />
      </div>
      <div v-if="data.label == '合计服务费'" style="color: red"> ￥{{ props.price }} </div>
    </template>
  </a-descriptions>
  <TakeOrderCom v-model="showTakeOrder" :type="props.type" @save="saveTakeOrder" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, inject, watch } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import useUserStore from '@/store/modules/user'
  import TakeOrderCom from './takeOrderCom.vue'
  import dayjs from 'dayjs'
  const props = defineProps(['type', 'price'])
  const emits = defineEmits(['saveCom', 'delCom'])
  const userInfo = useUserStore()
  const basicInfo = ref([
    { label: '任务创建人', value: '' },
    { label: '任务雇主', value: '', required: true },
    { label: '任务验收人', value: '' },
    { label: '期望交付日期', value: '' },
    // { label: '优先级', value: '' },
    { label: '接单组织', value: '' },
    { label: '合计服务费', value: '' },
  ])

  const levelList: any = ref([
    { label: '低', value: 'LOW' },
    { label: '中', value: 'MIDDLE' },
    { label: '高', value: 'HIGH' },
    { label: '急', value: 'URGENT' },
  ])

  const skuInfo: any = inject('skuInfo')
  const type: any = inject('type')
  const taskDetailInfo: any = inject('taskDetailInfo')

  let userList: any = ref([])
  let organizesUser = ref([])

  let form: any = ref({
    employer: {},
    verifyerList: [],
    takeCompany: {},
    priority: 'LOW',
    gmtExpectDelivery: '',
  })
  let showTakeOrder = ref(false)

  const changeUser: any = (val: string) => {
    let item: any = userList.value.find((item: any) => item.id == val)
    if (item) {
      form.value.employer.id = item.id
      form.value.employer.name = item.name
      if (form.value.verifyerList[0].id != item.id) {
        let obj = {
          id: item.id,
          name: item.name,
        }
        form.value.verifyerList.splice(1, 1, obj)
      } else {
        form.value.verifyerList.splice(1, 1)
      }
    }
  }

  const saveTakeOrder: any = (val: any) => {
    form.value.takeCompany = {}
    form.value.takeCompany.id = val.companyId
    form.value.takeCompany.companyShortName = val.companyShortName
    emits('saveCom', val)
  }

  const addCreateUserName = () => {
    let obj = {
      id: userInfo.userId,
      name: userInfo.userName,
    }
    form.value.verifyerList.push(obj)
  }
  // 获取表单数据
  const getOrSetForm = (info: any) => {
    if (!info) {
      if (!form.value.employer.id) {
        Message.error('请选择任务雇主')
        return false
      }
      // if (!form.value.takeCompany.companyName) {
      //   Message.error('请选择接单组织')
      //   return false
      // }
      return form.value
    } else {
      form.value.priority = info.priority
      form.value.gmtExpectDelivery = dayjs(info.gmtExpectDelivery).valueOf()
      form.value.employer = info.employer
      form.value.verifyerList = info.verifyerList
      form.value.takeCompany = info.takeCompany
    }
  }

  const disableDate = (current: any) => {
    return dayjs(new Date(current).valueOf() + 24 * 60 * 60 * 1000).isBefore(dayjs())
  }

  const getUserList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    organizesUser.value = res.data.records.map((e: any) => {
      e.name = e.userName
      return e
    })
  }

  const comSave = (info: any) => {
    form.takeCompany.id = info.companyId
    form.takeCompany.companyShortName = info.companyShortName
  }

  const delCom = () => {
    form.value.takeCompany = {}
    emits('delCom')
  }

  // 提前调用获取用户列表
  getUserList()

  onMounted(() => {
    // 填入创建人信息
    addCreateUserName()
    // form.value.gmtExpectDelivery = new Date().getTime() + 3 * 24 * 60 * 60 * 1000
  })

  watch(
    () => skuInfo.value,
    (val) => {
      if (type == 'add') {
        form.value.employer = {
          id: '',
          name: '',
        }
        form.value.verifyerList = []
        addCreateUserName()
      }
      if (val?.salerList && val?.salerList[0]) {
        userList.value = val?.salerList || []
        let obj = {
          id: userList.value[0].id,
          name: userList.value[0].name,
        }
        form.value.employer = obj
        changeUser(userList.value[0].id)
      } else {
        // 编辑的时候是否给任务雇主所有用户
        let timer = setInterval(() => {
          if (organizesUser.value[0]) {
            clearInterval(timer)
            userList.value = organizesUser.value
            if (type == 'add') {
              let obj = {
                id: userInfo.userId,
                name: userInfo.userName,
              }
              form.value.employer = obj
            }
          }
        }, 1)
      }
    },
    { deep: true }
  )

  defineExpose({ getOrSetForm, getUserList, form })
</script>

<style lang="less" scoped>
  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .level-item {
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background-color: #d7d7d7;
    border-radius: 3px;
    margin-right: 5px;
    color: #aaaaaa;
    font-size: 12px;
  }

  .active {
    background-color: rgb(var(--primary-6));
    color: white;
  }
</style>
